#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include<string>
#include "ringqueue.hpp"
#include"Task.hpp"
// using namespace std;
RingQueue<Task> *rq = new RingQueue<Task>(5);
class ThreadDate
{
public:
    ThreadDate(string threadName) : threadName_(threadName)
    {}

    ThreadDate()
    {}

    string* ThreadName()
    {
        return &threadName_;
    }
    pthread_t* Id()
    {
        return &id_;
    }

private:
    string threadName_;
    pthread_t id_;
};

void *Consumer(void *rags)
{
    ThreadDate* c=static_cast<ThreadDate*>(rags);

    while (true)
    {
        // int out = 0;
        // rq->Pop(&out);
        // cout<<*c->ThreadName() << "消费了一个数据：" << out << endl;
        // sleep(1);
        Task t;
        rq->Pop(&t);
        t.Run();
        cout<<*c->ThreadName()<<"完成了一个任务："<<t.x_<<t.op_<<t.y_<<"="<<t.result_<<" exitcode："<<t.exitcode_<<endl;
        sleep(1);
    }
};

void *Producer(void *rags)
{
    ThreadDate* p=static_cast<ThreadDate*>(rags);
    //sleep(1);
    while (true)
    {
        // int date = rand()%10;
        // rq->Push(date);
        // cout<<*p->ThreadName() << "生产了一个数据：" << date << endl;
        //sleep(1);
        Task t(rand()%10+1,rand()%10+1,opers[rand()%5]);
        rq->Push(t);
        cout<<*p->ThreadName()<<"生产了一个任务："<<t.x_<<t.op_<<t.y_<<"=???"<<endl;
        //sleep(1);

    }
}

 
int main()
{
   srand(time(nullptr));
    // pthread_t c;
    // pthread_t p;
    // pthread_create(&c,nullptr,Consumer,rq);
    // pthread_create(&p,nullptr,Producer,rq);

    // pthread_join(c,nullptr);
    // pthread_join(p,nullptr);
    ThreadDate c[3];
    ThreadDate p[5];
    for (int i = 0; i < 3; i++)
    {
        *c[i].ThreadName()="c_thread"+to_string(i);
        pthread_create(c[i].Id(),nullptr,Consumer,&c[i]);
    }
    for(int i=0;i<5;i++)
    {
        *p[i].ThreadName()="p_thread"+to_string(i);
        pthread_create(p[i].Id(),nullptr,Producer,&p[i]);
    }

    for(int i=0;i<3;i++)
    {
        pthread_join(*c[i].Id(),nullptr);
    }
    for(int i=0;i<5;i++)
    {
        pthread_join(*p[i].Id(),nullptr);
    }


}